<template>
  <view>
    <view class="spec-set page100 flex-col" :style="{ '--theme': themeColor }">
      <nav-bar title="规格设置" />
      <view class="top flex text-29 marginBottom-20" ref="top">
        <view
          :class="['flex1', 'center', 'tab', index === active ? 'active' : '']"
          v-for="(item, index) in tabList"
          :key="index"
          @click="changeTab(index)"
          >{{ item }}</view
        >
      </view>
      <view class="list flex1 flex-col" v-if="active == 0">
        <scroll-view scroll-y class="flex1" v-if="specList.length > 0">
          <view v-for="(item, index) in specList" :key="index">
            <spec-com
              :spec="item"
              @upData="getData"
              @addAttr="addAttr($event, index)"
              @deleteAttr="deleteAttr($event, index)"
              @deleteSpec="deleteSpec($event, index)"
              @editSpecTitle="editSpecTitle(index, item)"
            />
          </view>
        </scroll-view>
        <xh-empty title="暂无相关规格数据" class="flex1" v-else />
      </view>
      <view class="list flex1 flex-col" v-else>
        <view v-if="showTabSku" class="flex1 flex-col">
          <view class="shop" @click="showPop()" v-if="type == 'edit'">
            <!-- :style="{
              opacity: !pubUserInfo.mainShopStatus ? '0.7' : '',
            }" -->
            <u--input
              disabledColor="#fff"
              :disabled="true"
              placeholder="请输入内容"
              v-model="selectPar.storeName"
              suffixIcon="arrow-down"
            />
          </view>
          <scroll-view
            @scrolltolower="upList"
            lower-threshold="200px"
            class="flex1"
            v-if="skuList.length > 0"
            scroll-y
            @scroll="scrollViewMethod"
          >
            <view v-for="(item, index) in showList" :key="`${index}`">
              <u--form
                :model="showList[index]"
                :rules="rules"
                :ref="`form_${index}_ref`"
                labelWidth="70px"
              >
                <view class="flex sku">
                  <view class="flex1">
                    <view class="flex flexAIC sku-top">
                      <view class="flex1 flex">
                        <view
                          class="title flex flexAIC"
                          @click="changeCheck(index)"
                        >
                          <view
                            v-show="isBatch"
                            :class="[
                              'check center',
                              checkBoxList[index] ? 'isCheck' : '',
                            ]"
                          >
                            <u-icon
                              size="14"
                              color="#ffffff"
                              name="checkbox-mark"
                              v-if="checkBoxList[index]"
                            />
                          </view>

                          {{
                            item.specAttrNameList
                              .toString()
                              .split(",")
                              .join("/")
                          }}</view
                        >
                        <view class="flex flex1 flex-end">
                          <view class="marginRight-13">上下架</view>
                          <u-switch
                            v-model="showList[index].status"
                            :activeValue="1"
                            :inactiveValue="0"
                            inactiveColor="#dcdfe6"
                            size="19"
                          />
                        </view>
                      </view>
                    </view>
                    <u-form-item prop="price" label="价格/元">
                      <u--input
                        type="digit"
                        v-model="showList[index].price"
                        maxlength="9"
                        :showWordLimit="true"
                        placeholder="请输入售卖价格"
                        :formatter="formatter"
                        clearable
                      />
                    </u-form-item>
                    <u-form-item label="库存" prop="inventory">
                      <u--input
                        type="number"
                        v-model.trim="showList[index].inventory"
                        maxlength="6"
                        :showWordLimit="true"
                        placeholder="请输入售卖库存"
                        clearable
                      />
                    </u-form-item>
                  </view>
                </view>
              </u--form>
            </view>
          </scroll-view>
        </view>
        <xh-empty title="请先添加规格" class="flex1" v-if="!showTabSku" />
      </view>
      <view class v-if="!isBatch">
        <view class="bottom flex" v-if="active === 0">
          <u-button
            v-if="pubUserInfo.mainShopStatus"
            class="batch-btn"
            @click="clearSpec()"
            >{{ specList.length > 0 ? "清空规格并保存" : "保存" }}
          </u-button>
          <u-button
            v-if="pubUserInfo.mainShopStatus && specList.length < 3"
            type="primary"
            @click="showAdd = true"
            >添加规格
          </u-button>
          <u-button
            v-if="pubUserInfo.mainShopStatus && specList.length > 2"
            type="primary"
            :disabled="true"
            @click="showAdd = true"
            >添加规格
          </u-button>
        </view>
        <view class="bottom flex" v-if="active === 1 && showTabSku">
          <u-button class="batch-btn" @click="isBatch = true"
            >批量操作</u-button
          >
          <u-button type="primary" @click="save()">保存</u-button>
        </view>
      </view>
      <view class="batch flex flexAIC" v-else>
        <view class="radio flex flexAIC text-28" @click="changeAllBox()">
          <view :class="['check center', isAll ? 'isCheck' : '']">
            <u-icon
              size="14"
              color="#ffffff"
              name="checkbox-mark"
              v-if="isAll"
            />
          </view>
          全选
        </view>
        <view class="flex flex1 flex-end batch-btns flexAIC">
          <view @click="isBatch = false">退出批量</view>
          <view
            @click="showBatch()"
            :class="[disabledBatch ? 'active' : 'disable']"
          >
            批量修改
          </view>
        </view>
      </view>
    </view>
    <add-spec-val
      :visible.sync="showAdd"
      :specList="specList"
      @addSpec="addSpec"
      :editSpecForm.sync="editSpecForm"
    />
    <choose-shop
      :visible.sync="showChoose"
      @chooseClass="chooseShop"
      :activeStoreId="selectPar.shopId"
      :isShowAll="false"
      activeFiled="shopId"
    />
    <batch-modal :visible.sync="showBatchModal" @submitBatch="submitBatch" />
  </view>
</template>
<script>
import specCom from "@/components/pageComponents/sp-product/spec-com";
import addSpecVal from "@/components/pageComponents/sp-product/add-spec";
import { chooseShop } from "@/components/pageComponents/sp-product/choose-shop";

import skuCom from "@/components/pageComponents/sp-product/sku-com";
import batchModal from "@/components/pageComponents/sp-product/batch-modal";
import { getStoreList } from "@/service/api/sp-product/index";
import { mapState, mapActions } from "vuex";
import { regexp } from "@/utils/regexp";
import result from "autoprefixer/data/prefixes";

export default {
  components: {
    addSpecVal,
    specCom,
    chooseShop,
    skuCom,
    batchModal,
  },
  data() {
    return {
      rules: {
        price: [
          // {
          //   type: "number",
          //   required: true,
          //   message: "此为必填字段",
          //   trigger: ["blur", "change"],
          // },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              return !(value == '0');
            },
            message: "请输入区间0.01-999999.99",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
          {
            pattern: /^([1-9]\d{0,5}|0)(\.\d{1,2})?$|^1000000(\.0{1,2})?$/,
            transform(value) {
              return String(value);
            },
            message: "请输入区间0.01-999999.99",
          },
        ],
        inventory: [
          {
            type: "number",
            required: true,
            message: "此为必填字段",
            trigger: ["blur", "change"],
          },
        ],
      },
      active: 0, // tab值
      tabList: ["规格", "价格/库存"],
      isBatch: false,
      isAll: false,
      skuList: [],
      specList: [],
      checkedList: [],
      showBatchModal: false,
      storeLists: [],
      showAdd: false,
      showChoose: false,
      selectPar: {
        name: "",
        shopId: "",
      },
      type: "add",
      showTabSku: true,
      editSpecForm: {},
      temporaryArr: [],
      checkBoxList: [],
      pagePar: {
        page: 1,
        pageSize: 6,
        total: 0,
      },
      showList: [],
      disabledBatch: false,
    };
  },
  async mounted() {
    this.active = +this?.$Route?.query?.activeTab;
    this.type = this?.$Route?.query?.type;
    this.skuList = JSON.parse(JSON.stringify(this.vxSkus));
    this.specList = JSON.parse(JSON.stringify(this.vxspecList));
    this.storeLists = JSON.parse(JSON.stringify(this.vxstoreList));
    await this.getStoreList();
    await this.initStrolist();
  },
  computed: {
    currentShopIndex() {
      return this.storeLists.findIndex((item) => {
        return item.shopId == this.selectPar.shopId;
      });
    },
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
    ...mapState("sp-common/auth", ["pubUserInfo"]),
    ...mapState("sp-product/index", {
      vxSkus: "skuList",
      vxspecList: "specList",
      vxstoreList: "storeList",
    }),
  },
  watch: {
    "selectPar.shopId"(val) {
      if (this.skuList.length > 0) {
        this.resetQuery();
        this.setSelfRules(1);
      }
    },
    specList: {
      handler(newVal) {
        this.checkSpec();
      },
      deep: true,
    },
    checkBoxList: {
      handler(newVal) {
        this.disabledBatch = newVal.indexOf(true) > -1;
      },
      deep: true,
    },
  },

  methods: {
    ...mapActions("sp-product/index", [
      "setSkuList",
      "setSpecList",
      "setStoreList",
    ]),
    // tab切换
    changeTab(index) {
      if (index == this.active) return;
      this.isBatch = false;
      this.active = index;
      if (this.active == 1) {
        this.resetQuery();
      }
    },
    // 获取门店列表
    getStoreList() {
      return new Promise((resolve) => {
        getStoreList({ disabled: false }).then((res) => {
          this?.vxstoreList?.length <= 0 ? (this.storeLists = res) : "";
          let {
            pubUserInfo: { shopId: pubShopId },
          } = this;
          let defaultPar = "";
          if (this?.vxstoreList?.length > 0) {
            let index = this.vxstoreList.findIndex((ele) => {
              return ele.shopId == pubShopId;
            });
            defaultPar = this.vxstoreList[index];
          } else {
            let index = res.findIndex((ele) => {
              return ele.shopId == pubShopId;
            });
            defaultPar = res[index];
          }
          let { shopId, storeName } = defaultPar;
          this.selectPar = {
            shopId,
            storeName,
          };
          this.pagePar.total = this?.skuList?.length;
          resolve();
        });
      });
    },
    // 批量修改
    submitBatch(batchForm) {
      let { price, inventory, isOpen } = batchForm;
      let { checkBoxList, currentShopIndex, isAll } = this;
      if (isAll) {
        this.storeLists[currentShopIndex].skus.forEach((item, index) => {
          if (price) {
            this.storeLists[currentShopIndex].skus[index].price = price;
          }
          if (inventory) {
            this.storeLists[currentShopIndex].skus[index].inventory = inventory;
          }
          this.storeLists[currentShopIndex].skus[index].status = isOpen;
        });
      } else {
        if (checkBoxList.length > 0) {
          checkBoxList.forEach((item, index) => {
            if (item) {
              // this.storeLists[currentShopIndex].skus[index].price = price;
              this.storeLists[currentShopIndex].skus[index].status = isOpen;
              // this.storeLists[currentShopIndex].skus[index].inventory =
              //   inventory;
              if (price) {
                this.storeLists[currentShopIndex].skus[index].price = price;
              }
              if (inventory) {
                this.storeLists[currentShopIndex].skus[index].inventory =
                  inventory;
              }
            }
          });
        }
      }
      this.isAll = false;
      this.isBatch = false;
      this.changeAllBox(1);
    },
    // 添加规格
    addSpec(row) {
      row.attrList = [];
      this.specList.push(row);
      this.skuBuilder();
      this.resetQuery();
    },
    // 添加规格值
    addAttr(e, index) {
      this.specList[index].attrList.push(e);
      this.initStrolist();
    },
    // 保存
    save() {
      let { $refs, type } = this;
      let statusNum = 0;
      let forms = Object.keys($refs).filter((ele) => {
        return ele.indexOf("form") > -1;
      });

      const res = forms.map(async (item, index) => {
        let sta = await this.$refs[item][0].validate();
        if (sta) statusNum++;
        return item;
      });
      Promise.allSettled(res).then(async () => {
        if (forms.length === statusNum) {
          if (type == "edit") {
            let isVerify = await this.verifySpec();
            if (Object.keys(isVerify).length > 0) {
              uni.showModal({
                content: `保存失败，${isVerify.name}：${isVerify.specName}未配置价格/库存`,
                showCancel: false,
                confirmText: "我知道了",
                confirmColor: this.themeColor,
              });
              return;
            }
          }
          this.saveSpecs().then(() => {
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2]; //上一页页面实例
            prevPage.$vm.saveSpec();
            uni.navigateBack({
              delta: 1,
            });
          });
        }
      });
    },
    // 生成sku
    skuBuilder() {
      return new Promise((resolve) => {
        const specList = JSON.parse(JSON.stringify(this.specList));
        const attrIdsArr = [];
        const attrNameObj = {};
        specList.forEach((spec, specIndex) => {
          const attrIds = [];
          spec.attrList.forEach((attr, attrIndex) => {
            attrIds.push(attr.id);
            attrNameObj[attr.id] = attr.title;
          });
          attrIdsArr.push(attrIds);
        });
        // 获取sku所有组合
        const skuIdsArr = skuList(...attrIdsArr);
        // 生成table列表 匹配原有表格数据存在则不插新数据
        const tableListNew = [];
        skuIdsArr.forEach((idsArr) => {
          const specAttrNameList = [];
          const skuObj = {
            imgUrl: "",
            originPrice: "",
            price: "",
            skuNo: "",
            sn: "",
            inventory: 0,
            specAttrNameList: [],
            specAttrIdsList: idsArr,
            status: 0,
            specAttr1: 0,
            specAttr2: 0,
            specAttr3: 0,
            specAttr4: 0,
            specAttr5: 0,
            specAttr6: 0,
          };
          idsArr.forEach((id, idIndex) => {
            specAttrNameList.push(attrNameObj[id]);
            skuObj["specAttr" + (idIndex + 1)] = id;
          });
          skuObj.specAttrNameList = specAttrNameList;
          tableListNew.push(skuObj);
        });
        // 判断是否已经存在 存在则使用旧数据
        tableListNew.forEach((newItem, newItemIndex) => {
          this.skuList.forEach((oldItem) => {
            const newItemString = JSON.stringify(
              newItem.specAttrNameList.sort()
            );
            const oldItemString = JSON.stringify(
              oldItem.specAttrNameList.sort()
            );
            if (newItemString === oldItemString) {
              tableListNew.splice(newItemIndex, 1, oldItem);
            }
          });
        });

        // 赋值
        this.skuList = tableListNew;
        // 生成所有sku组合
        function skuList() {
          return Array.prototype.reduce.call(
            arguments,
            function (a, b) {
              if (b.length === 0) {
                return a;
              }
              let ret = [];
              a.forEach(function (a) {
                b.forEach(function (b) {
                  ret.push(a.concat([b]));
                });
              });
              return ret;
            },
            [[]]
          );
        }
        resolve();
      });
    },
    // 初始化门店所有sku
    async initStrolist() {
      await this.skuBuilder();
      let { skuList, storeLists } = this;
      // let storeLists = JSON.parse(JSON.stringify(this.storeLists));
      // this.storeLists=[]
      storeLists.forEach((ele, index) => {
        let cloneSkuList = JSON.parse(JSON.stringify(skuList));
        if (ele?.skus?.length > 0) {
          let childSkus = ele?.skus.map((ele) => {
            return ele?.specAttrNameList.sort().toString();
          });
          cloneSkuList.forEach((element, index) => {
            element.price = "";
            element.inventory = 9999;
            element.status = 1;
            if (
              childSkus.indexOf(element?.specAttrNameList.sort().toString()) >
              -1
            ) {
              cloneSkuList[index] =
                ele.skus[
                  childSkus.indexOf(element?.specAttrNameList.sort().toString())
                ];
            }
          });
          ele.skus = cloneSkuList;
        } else {
          ele.skus = cloneSkuList;
        }
      });
      this.storeLists = JSON.parse(JSON.stringify(storeLists));
      this.pagePar.total = this?.skuList?.length;
      this.resetQuery();
    },
    // 筛选门店
    chooseShop(data) {
      this.selectPar = data.storeData;
    },

    deleteAttr(e, index) {
      this.specList[index].attrList = e;
      this.initStrolist();
    },
    deleteSpec(e, index) {
      uni.showModal({
        content: "是否删除规格？删除后对应规格值也将一起删除，请谨慎操作",
        success: (res) => {
          if (res.confirm) {
            this.specList.splice(index, 1);
            this.initStrolist();
          }
        },
      });
    },
    saveSpecs() {
      return new Promise((resolve, reject) => {
        let { storeLists, skuList, specList, type, currentShopIndex } = this;
        let mainSkus = JSON.parse(
          JSON.stringify(storeLists[currentShopIndex]?.skus || [])
        );
        if (type == "add" || type == "copy") {
          // 如果是新增/复制    所有分店都是以主店的sku价格为准     sku列表也是以主店的为准
          if (storeLists.length > 0) {
            storeLists.forEach((ele) => {
              ele.skus = mainSkus;
            });
          }
        }
        skuList = mainSkus;
        this.setSkuList(skuList);
        this.setSpecList(specList);
        this.setStoreList(storeLists);
        resolve();
      });
    },
    checkSpec() {
      let { specList } = this;
      if (specList?.length <= 0) {
        this.showTabSku = false;
      } else {
        let falg = false;
        specList.forEach((ele) => {
          if (ele?.attrList?.length > 0) {
            falg = true;
          }
        });
        this.showTabSku = falg;
      }
    },
    showBatch() {
      if (this.checkBoxList.indexOf(true) < 0) return;
      this.showBatchModal = true;
    },
    formatter(value) {
      if (value.indexOf(".") > 0) {
        var re = /([0-9]+\.[0-9]{2})[0-9]*/;
        return value.replace(re, "$1");
      } else {
        return value;
      }
    },
    showPop() {
      if (!this.pubUserInfo.mainShopStatus) return;
      let { currentShopIndex, storeLists, falg = true } = this;
      storeLists[currentShopIndex].skus.forEach((ele) => {
        if (ele.inventory<=0 || ele.price <= 0 || !ele.price) falg = false;
      });
      if (!falg) {
        uni.showModal({
          content: "存在价格/库存未配置，请先完成配置",
          showCancel: false,
          confirmText: "我知道了",
          confirmColor: this.themeColor,
        });
        return;
      }
      this.showChoose = true;
    },
    editSpecTitle(index, item) {
      this.editSpecForm = Object.assign({}, { index, ...item });
      this.showAdd = true;
    },
    getShowList() {
      let {
        pagePar: { pageSize, page },
        storeLists,
        currentShopIndex,
        isAll,
      } = this;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      let nextPageData = storeLists[currentShopIndex].skus.slice(
        startIndex,
        endIndex
      );
      this.showList = this.showList.concat(nextPageData);
      nextPageData.forEach(() => {
        this.checkBoxList.push(isAll);
      });
      // if (page == 1) {
      this.setSelfRules();
      // }
    },
    upList() {
      let {
        pagePar: { total },
        showList,
      } = this;
      if (showList.length >= total) {
        return; // 如果当前已经加载完所有数据，则不再执行后续操作
      }
      this.pagePar.page++;
      this.getShowList();
    },
    changeCheck(index) {
      if (!this.isBatch) return;
      this.$set(this.checkBoxList, index, !this.checkBoxList[index]);
      const count = this.checkBoxList.reduce((acc, cur) => {
        if (cur) {
          acc++;
        }
        return acc;
      }, 0);
      this.$set(this, "isAll", this.checkBoxList.length == count);
    },
    changeAllBox(status) {
      // status 1 false 2 true
      if (status) {
        this.$set(this, "isAll", status == 1 ? false : true);
        this.checkBoxList.forEach((ele, index) => {
          this.$set(this.checkBoxList, index, status == 1 ? false : true);
        });
      } else {
        this.$set(this, "isAll", !this.isAll);
        this.checkBoxList.forEach((ele, index) => {
          this.$set(this.checkBoxList, index, this.isAll);
        });
      }
    },
    resetQuery() {
      this.pagePar.page = 1;
      this.$set(this, "showList", []);
      this.checkBoxList = [];
      this.getShowList();
      this.changeAllBox(1);
    },
    scrollViewMethod() {
      uni.hideKeyboard();
    },
    setSelfRules(type) {
      this.$nextTick(() => {
        let { $refs } = this;
        let forms = Object.keys($refs).filter((ele) => {
          return ele.indexOf("form") > -1;
        });
        forms.map((item, index) => {
          type
            ? this.$refs[item][0].clearValidate()
            : this.$refs[item][0].setRules(this.rules);
        });
      });
    },
    clearSpec() {
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2]; //上一页页面实例
      if (this.specList.length > 0) {
        uni.showModal({
          title: "",
          content: "是否确定清空规格并保存为无规格商品？",
          confirmColor: this.themeColor,
          success: (res) => {
            if (res.confirm) {
              this.skuList = [];
              this.specList = [];
              this.storeLists = [];
              this.saveSpecs().then(() => {
                prevPage.$vm.saveSpec();
                uni.navigateBack({
                  delta: 1,
                });
              });
            }
          },
        });
      } else {
        this.skuList = [];
        this.specList = [];
        this.storeLists = [];
        this.saveSpecs().then(() => {
          prevPage.$vm.saveSpec();
          uni.navigateBack({
            delta: 1,
          });
        });
      }
    },
    verifySpec() {
      return new Promise((resolve, reject) => {
        let falg = true;
        let storeLists = this.storeLists;
        let errmsg = {};
        if (storeLists.length >= 1) {
          for (let index = 0; index < storeLists.length; index++) {
            let eleSku = JSON.parse(JSON.stringify(storeLists[index].skus));
            if (eleSku.length > 0) {
              for (let j = 0; j < eleSku.length; j++) {
                if (
                  !eleSku[j].inventory ||
                  eleSku[j].price <= 0 ||
                  !eleSku[j].price
                ) {
                  falg = false;
                  errmsg = {
                    name: storeLists[index].storeName,
                    specName: eleSku[j].specAttrNameList
                      .toString()
                      .split(",")
                      .join("/"),
                  };
                  resolve(errmsg);
                }
              }
            }
          }
          if (falg) {
            resolve(falg);
          }
        }
      });
    },
  },
  // 临时保存数据
  beforeDestroy() {
    this.saveSpecs();
  },
};
</script>
<style lang="scss" scoped>
@import "../../css/spec-set.scss";
</style>
